package geral.converter;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

@FacesConverter(value="cnpjConverter" )
public class CnpjConverter implements Converter {

    @Override
    public Object getAsObject(FacesContext arg0, UIComponent arg1, String texto) {
        if (texto == null) {
            return null;
        }

        return texto.replaceAll("[^0-9]", "");
    }

    @Override
    public String getAsString(FacesContext arg0, UIComponent arg1, Object texto) {
    	if (texto == null) {
            return null;
        }

        String txt = texto.toString();

        if (txt.length() != 14) {
            return txt;
        }

        StringBuilder sb = new StringBuilder();
        sb.append(txt.substring(0, 2));
        sb.append('.');
        sb.append(txt.substring(2, 5));
        sb.append('.');
        sb.append(txt.substring(5, 8));
        sb.append('/');
        sb.append(txt.substring(8, 12));
        sb.append('-');
        sb.append(txt.substring(12, 14));
        
        return sb.toString();
    }
}
